﻿using RimWorld;
using Verse;
using Verse.AI;
using System.Collections.Generic;

namespace RimZombieGirl
{
    public class JobDriver_DigCursedGrave : JobDriver
    {
        private const int DigDuration = 1200; // 3000 tick
        public Building_CursedGrave TargetGrave => (Building_CursedGrave)TargetA.Thing;

        public override bool TryMakePreToilReservations(bool errorOnFailed)
        {
            return pawn.Reserve(TargetGrave, job, 1, -1, null, errorOnFailed);
        }

        protected override IEnumerable<Toil> MakeNewToils()
        {
            // 走到坟墓旁
            yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch);

            // 挖掘动作 Toil
            Toil digToil = new Toil();
            digToil.initAction = () =>
            {
                // 初始化累计 tick
                digToil.actor.jobs.curDriver.ticksLeftThisToil = DigDuration;
            };
            digToil.tickAction = () =>
            {
                pawn.skills.Learn(SkillDefOf.Construction, 0.05f);
            };
            digToil.defaultCompleteMode = ToilCompleteMode.Delay;
            digToil.defaultDuration = DigDuration;

            // 读条显示
            digToil.WithProgressBar(TargetIndex.A, () => 1f - (float)digToil.actor.jobs.curDriver.ticksLeftThisToil / DigDuration);

            // Toil 完成时调用 DigUp
            digToil.initAction = null; // 避免覆盖前面
            digToil.AddFinishAction(() =>
            {
                if (!TargetGrave.Destroyed)
                {
                    TargetGrave.CompCursedGrave.DigUp();
                }
            });

            yield return digToil;
        }
    }
}
